package com.autumn.platform.core.context.reqeust;

import org.springframework.core.NamedInheritableThreadLocal;
import org.springframework.core.NamedThreadLocal;

public abstract class RequestContextHolder {

    private static final ThreadLocal<IRequest> requestHolder =
            new NamedThreadLocal<IRequest>("Request");

    private static final ThreadLocal<IRequest> inheritableRequestHolder =
            new NamedInheritableThreadLocal<IRequest>("Request");

    /**
     * 重置请求信息
     */
    public static void resetRequest() {
        requestHolder.remove();
        inheritableRequestHolder.remove();
    }

    /**
     * 设置当前线程的请求信息
     * 
     * @param request
     */
    public static void setRequest(IRequest request) {
        setRequest(request, false);
    }

    /**
     * 设置当前线程及子线程请求信息
     * 
     * @param request
     * @param inheritable
     */
    public static void setRequest(IRequest request, boolean inheritable) {
        if (request == null) {
            resetRequest();
        } else {
            if (inheritable) {
                inheritableRequestHolder.set(request);
                requestHolder.remove();
            } else {
                requestHolder.set(request);
                inheritableRequestHolder.remove();
            }
        }
    }

    /**
     * 获取当前线程的请求信息
     * 
     * @return
     * @throws IllegalStateException
     */
    public static IRequest getRequest() throws IllegalStateException {
        IRequest request = requestHolder.get();
        if (request == null) {
            request = inheritableRequestHolder.get();
        }
        if (request == null) {
            throw new IllegalStateException("No thread-bound request found, please use RequestContextHolder.setRequest to expose the current request.");
        }
        return request;
    }
}
